package br.com.locanet.service;

import java.util.List;

import javax.persistence.PersistenceException;

import br.com.locanet.bean.IEntity;
import br.com.locanet.dao.GenericJPADAO;
import br.com.locanet.exception.ExceptionList;
import br.com.locanet.util.UtilReflection;

public abstract class AbstractEntityService<ENTITY extends IEntity, DAO extends GenericJPADAO<ENTITY>> implements EntityService<ENTITY>{
	@SuppressWarnings("unchecked")
	@Override
	public DAO getDAO() throws ClassNotFoundException {
		try {
			return (DAO) UtilReflection.getGenericClassType(getClass(), 1).newInstance();
		} catch (Exception e) {
			throw new ClassNotFoundException("erroInstanciarEntityDAO", e);
		}
	}
	
	public ENTITY insert(ENTITY entity) throws PersistenceException {
		try{
			doValidateRequiredFields(entity);
			doValidateBusinessRules(entity);
			return getDAO().insert(entity);
		}catch(Exception e){
			throw new PersistenceException(e);
		}
	}
	
	public void delete(ENTITY entity) throws PersistenceException {
		try{
			getDAO().delete(entity);
		}catch(Exception e){
			throw new PersistenceException(e);
		}
	}
	
	public ENTITY update(ENTITY entity) throws PersistenceException  {
		try{
			doValidateRequiredFields(entity);
			doValidateBusinessRules(entity);
			return getDAO().update(doMerge(entity));
		}catch(Exception e){
			throw new PersistenceException(e);
		}
	}
	
	public List<ENTITY> select(ENTITY entity) throws PersistenceException {
		try{
			return getDAO().find(entity);
		}catch(Exception e){
			throw new PersistenceException(e);
		}
	}
	
	public void doValidateRequiredFields(ENTITY entity) throws ExceptionList {}
	
	@Override
	public List<ENTITY> selectAll() throws PersistenceException{
		try{
			return getDAO().findAll();
		}catch(Exception e){
			throw new PersistenceException(e);
		}
	}
	
	@Override
	public ENTITY selectById(ENTITY entity) throws PersistenceException {
		try{
			return getDAO().findById(entity);
		}catch(Exception e){
			throw new PersistenceException(e);
		}
	}
	protected ENTITY doMerge(ENTITY entity) throws PersistenceException {
		return entity;
	}
	
}
